package demo1;

/**
 * 用LinkedList实现队列
 */
public class MyQueue {
    static class ListNode {
        private final int val;
        private ListNode prev;
        private ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode first;
    public ListNode last;

    /**
     *进行入队操作（尾插法）
     */
    public void offer(int data) {
        ListNode node = new ListNode(data);
        if(isEmpty()) {
            first = node;
            last = node;
        }
        last.next = node;
        node.prev = last;
        last = last.next;
    }

    /**
     *进行出队操作,获取队头的元素 并 删除(删除头节点)
     * @return
     */
    public int poll() {
        if(isEmpty()) {
            return  -1;
        }
        int value = first.val;
        if(first == last) {
            first = null;
            last = null;
        }else {
            first = first.next;
            first.prev = null;
        }
        return value;
    }

    /**
     *获取队头的元素 不 删除
     * @return
     */
    public int peek() {
        if(isEmpty()) {
            return  -1;
        }
        return first.val;
    }

    /**
     * 队列中的元素个数
     * @return
     */
    public int size() {
        ListNode cur = first;
        int count = 0;
        while (cur != null) {
            cur = cur.next;
            count++;
        }
        return count;
    }

    /**
     * 判断队列是否为空
     * @return
     */
    public boolean isEmpty() {
        return first == null;
    }
}
